package com.lucaswangdev.controller;

import com.lucaswangdev.entity.User;
import com.lucaswangdev.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户业务控制器
 */
@RequestMapping("/user")
@Controller
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /*添加 User*/
    @RequestMapping("/add")
    @ResponseBody
    public String add() {
        // 创建对象 方式1：
        // User user = new User(null,"张三22","男", "深圳");

        // 创建对象 方式2：
        User user = new User();
        user.setUsername("张三");
        user.setSex("男");
        user.setAddress("深圳");
        userMapper.insert(user);
        return "ok";
    }

    /*批量添加 User*/
    @RequestMapping("/batchAdd")
    @ResponseBody
    public String batchAdd() {
        // 创建对象 方式1：
        // User user = new User(null,"张三22","男", "深圳");
        List<User> list = new ArrayList<>();
        User e = new User();
        /*插入五条*/
        for (int i = 1; i <= 5; i++) {
            e.setUsername("name" + i);
            e.setSex("男");
            e.setAddress("地址：xxx" + i);
            list.add(e);
        }
        userMapper.insertList(list);
        return "insertList ok";
    }

    /*添加 User*/
    @RequestMapping("/update")
    @ResponseBody
    public String update() {
        // 创建对象 方式1：
        // User user = new User(null,"张三22","男", "深圳");

        // 创建对象 方式2：
        User user = new User();
        user.setId(8);
        user.setUsername("张三-8");
        user.setSex("男");
        // user.setAddress("深圳-8");
        userMapper.updateByPrimaryKeySelective(user);
        return "ok";
    }

    /**
     * 查询全部
     * @return
     */
    @RequestMapping("/getAll")
    @ResponseBody
    public List<User> getUserList() {
        Example example = new Example(User.class);
        userMapper.selectByExample(example);
        return userMapper.selectAll();
    }

    /**
     * 查询全部
     * @return
     */
    @RequestMapping("/getById")
    @ResponseBody
    public User getUserById() {
        User user = new User();
        user.setId(1);
        return userMapper.selectByPrimaryKey(user);
    }

    /*删除 User*/
    @RequestMapping("/delete")
    @ResponseBody
    public String delete() {
        // 创建对象 方式2：
        User user = new User();
        user.setId(7);
        Integer integer = userMapper.deleteByPrimaryKey(user);
        return "ok"  + integer;
    }
}
